package com.xuecheng.teaching.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.ReplyCommentDto;
import com.xuecheng.commons.model.vo.CommentReplyVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.UserVo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.system.api.SystemClient;
import com.xuecheng.teaching.domain.CommentReply;
import com.xuecheng.teaching.mapper.CommentReplyMapper;
import com.xuecheng.teaching.service.CommentReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-13
 */
@Service
public class CommentReplyServiceImpl extends ServiceImpl<CommentReplyMapper, CommentReply> implements CommentReplyService {

    @Autowired
    private SystemClient systemClient;

    //教育机构---课程评论回复
    @Override
    public ResponseResult commentReply(ReplyCommentDto dto) {
        //1.参数校验
        if (ObjectUtil.isEmpty(dto.getCommentId())){
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //2. 转为实体
        CommentReply commentReply = BeanHelper.copyProperties(dto, CommentReply.class);

        //2-1 调用feign
        ResponseResult<UserVo> responseResult = systemClient.phone();
        //2-2判断
        if (responseResult.getCode()!=0){
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //2-3 取出信息
        UserVo userVo = responseResult.getData();

        //3. 补全信息
        commentReply.setUserId(AuthInfoHolder.getUserId()); //用户id
        commentReply.setNickName(userVo.getName()); //设置昵称
        commentReply.setReplyDate(DateUtil.now());  //补全回复时间
        commentReply.setCommentId(dto.getCommentId().longValue());  //设置commentId
        //TODO  若多个评论则设置parentId,暂时不涉及
        //4.存入数据库
        this.save(commentReply);
        //5. 转vo
        CommentReplyVo vo = BeanHelper.copyProperties(commentReply, CommentReplyVo.class);
        //5.返回
        return ResponseResult.okResult(vo);
    }
}
